<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection" :scroll="{ x: false }" :data="dataARR">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" v-auth="'lx:xl_customer_orde:add'" @click="handleAdd" v-if="getProps()"
          preIcon="ant-design:plus-outlined"> 新增</a-button>
        <a-button type="primary" v-auth="'lx:xl_customer_orde:exportXls'" v-if="getProps()"
          preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
        <j-upload-button type="primary" v-auth="'lx:xl_customer_orde:importExcel'" v-if="getProps()"
          preIcon="ant-design:import-outlined" @click="onImportXls" @change="onHandleChange">
          导入</j-upload-button>
        <a-button type="default"
          @click="handleExportXlsx('采购订单导入', '/xl/template/downloadTemplateXls?template=ordercreate')"
          v-if="getProps()">
          <Icon icon="line-md:download-off-loop" />下载模板
        </a-button>


        <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="importLogiCode"
          v-if="getProps('6')" v-auth="'slt:logisticpackagemana:import'">导入物流信息</j-upload-button>


        <a-button type="default" v-auth="'slt:logisticpackagemana:templatedownload'" v-if="getProps('6')"
          @click="handleExportXls('上传物流信息', '/xl/template/downloadTemplateXls?template=deliveryCodeImport')">
          <Icon icon="line-md:download-off-loop" />下载物流回传模板
        </a-button>

        <!-- <a-progress v-if="uploading" :percent="percent" status="active" />
         -->
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete" v-auth="'lx:xl_customer_orde:deleteBatch'"
                v-if="getProps()">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
              <a-menu-item key="2" @click="batchHandleSumbit" v-auth="'lx:xl_customer_orde:sumbit'" v-if="getProps()">
                <Icon icon="ant-design:edit-outlined"></Icon>
                提交
              </a-menu-item>
              <a-menu-item key="3" @click="batchHandleAudit" v-auth="'lx:xl_customer_orde:audit'" v-if="getProps('1')">
                <Icon icon="ant-design:edit-outlined"></Icon>
                订单审核
              </a-menu-item>
              <a-menu-item key="4" @click="batchHandlePayment" v-auth="'lx:xl_customer_orde:payment1'"
                v-if="getProps('4')">
                <Icon icon="ant-design:edit-outlined"></Icon>
                支付确认
              </a-menu-item>
            </a-menu>
          </template>
          <a-button>批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
        <!-- 高级查询 -->
        <!-- <super-query :config="superQueryConfig" @search="handleSuperQuery" /> -->
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
      <!--字段回显插槽-->

      <template #orderStatusSlots="{ text, record }">
        <a-tag v-if="record.orderStatus == '待提交'" color='#CCCCCC'>{{ text }}</a-tag>
        <a-tag v-if="record.orderStatus == '待支付'" color='#FFA500'>{{ text }}</a-tag>
        <a-tag v-if="record.orderStatus == '待审核'" color='#FFD700'>{{ text }}</a-tag>
        <a-tag v-if="record.orderStatus == '待发货'" color='#ADD8E6'>{{ text }}</a-tag>
        <a-tag v-if="record.orderStatus == '待收货'" color='#40E0D0'>{{ text }}</a-tag>
        <a-tag v-if="record.orderStatus == '已收货'" color='#2E8B57'>{{ text }}</a-tag>
        <a-tag v-if="record.isDebt == '欠款送审'" color='#ff2d51'>{{ record.isDebt }}</a-tag>
      </template>
      <template #receiptinfo="{ text, record }">
        <div>门店编号：{{ record.storeCode }}</div>
        <div>门店名称：{{ record.storeName }}</div>
      </template>
      <template #orderDataRender="{ text, record }">
        <div>商品数量：{{ record.totalNum }}个/{{ record.detailNum }}种</div>
        <div>订单金额：{{ record.totalAmount }}</div>
        <div>售后金额：{{ record.totalAfterAmount }}</div>
        <div>应收金额：{{ record.totalRealAmount }}</div>
        <div v-if="record.paymentAmount" style="background-color:#f00056;">实收金额：{{ record.paymentAmount }}</div>
      </template>


      <template #createInfoRender="{ text, record }">
        <div>创建人：{{ record.createBy }}</div>
        <div>创建时间：{{ record.createTime }}</div>
        <div v-if="record.paymentTime" style="color:red;">支付时间：{{ record.paymentTime }}</div>
        <div v-if="record.orderNotes">订单备注：{{ record.orderNotes }}</div>
      </template>
      <template #auditInfoRender="{ text, record }">
        <a-tag v-if="record.auditState == '0'" color='yellow'>审批状态：{{ record.auditState_dictText }}</a-tag>
        <a-tag v-if="record.auditState == '1'" color='green'>审批状态：{{ record.auditState_dictText }}</a-tag>
        <a-tag v-if="record.auditState == '2'" color='red'>审批状态：{{ record.auditState_dictText }}</a-tag>
        <a-tag v-if="record.auditState == '-1'" color='blue'>审批状态：{{ record.auditState_dictText }}</a-tag>
        <div>审核时间：{{ record.auditTime }}</div>
        <div>审核人：{{ record.auditBy }}</div>
        <div>审核意见：{{ record.auditNote }}</div>
      </template>
      <template #payInfoRender="{ text, record }">
        <a-tag v-if="record.paymentState == '0'" color='red'>支付状态：{{ record.paymentState_dictText }}</a-tag>
        <a-tag v-if="record.paymentState == '1'" color='green'>支付状态：{{ record.paymentState_dictText }}</a-tag>
        <div>支付时间：{{ record.paymentTime }}</div>
      </template>
      <template #shipmentInfoRender="{ text, record }">
        <a-tag color='red'>发货状态：{{ record.orderStatus }}</a-tag>
        <div>发货时间：{{ record.shipmentTime }}</div>
      </template>

      <template v-slot:bodyCell="{ column, record, index, text }">
        <template v-if="column.dataIndex === 'orderCode'">
          <!--订单运输类型-->

          {{ text }}<a href="javascript:void(0)" @click="copys(text)">
            <Icon icon="solar:copy-outline"></Icon>
          </a>
          <div v-if="record.kmSid">Sid：{{ record.kmSid }}<a href="javascript:void(0)" @click="copys(record.kmSid)">
              <Icon icon="solar:copy-outline"></Icon>
            </a></div>
          <p>
            <a-tag v-if="record.deliveryWay == '1'" color='red'>城配</a-tag>
            <a-tag v-else-if="record.deliveryWay == '2'" color='green'>一件代发</a-tag>

          </p>
        </template>
      </template>
      <template #expandedRowRender="{ record }">
        <div>收件人：{{ record.receiptName }} - {{ record.receiptPhone }}</div>
        <div>地址：{{ getAreaTextByCode(record.receiptZone) }} {{ record.receiptAddress }} </div>
        <div v-if="record.deliveryCodes"> 物流单号：
          <a-tag v-for="(item, index) in record.deliveryCodes?.split(',')">

            <a href="javascript:void(0)" @click="handleDetailS(record.orderCode, item)">{{ item }}
              <Icon icon="icon-park:click" />
            </a>
          </a-tag>
        </div>
      </template>

      <template #expandColumnTitle>
        <span style="color: red">更多</span>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <AllModal @register="submitPaymentModal" :schemas="zhifupinzhengFormSchema" :apiUrl="submitPayment" :height="320"
      @success="handleSuccess" />
    <AllModal @register="submitAuditModal" :schemas="auditFormSchema" :apiUrl="audit" :height="150"
      @success="handleSuccess" />
    <XlCustomerOrdeModal @register="registerModal" @success="handleSuccess"></XlCustomerOrdeModal>
    <XlCustomerOrdeShipmentModal @register="registerModal2" @success="handleSuccess"></XlCustomerOrdeShipmentModal>
    <billLogDraw @register="registerBillLogDraw"></billLogDraw>
    <LogisticDetail @register="registerDetailModal1"></LogisticDetail>
  </div>
</template>

<script lang="ts" name="lx-xlCustomerOrde" setup>
import { ref, reactive, onMounted, unref, computed } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage'
import { useModal } from '/@/components/Modal';
import XlCustomerOrdeModal from './components/XlCustomerOrdeModal.vue'
import XlCustomerOrdeShipmentModal from './components/XlCustomerOrdeShipmentModal.vue'

import LogisticDetail from '../logicmana/components/LogisticDetail.vue';

import { columns, searchFormSchema, uniFormSchema,superQuerySchema, pageType, zhifupinzhengFormSchema,auditFormSchema } from './XlCustomerOrde.data';
import { list, deleteOne, batchDelete, getImportUrl, getExportUrl, shipment, payment, audit, downloadTemplateXlsUrl, exportPdfStream, submitPayment, submitTakeDelivery,sumbitOk,shouhuo } from './XlCustomerOrde.api';
import { downloadFile } from '/@/utils/common/renderUtils';
import { useUserStore } from '/@/store/modules/user';
import { getAreaTextByCode } from '/@/components/Form/src/utils/Area';
import { useMessage } from "/@/hooks/web/useMessage";
import { useMethods } from '/@/hooks/system/useMethods';
import AllModal from './components/AllModal.vue';
import { useDrawer } from '/@/components/Drawer';
import billLogDraw from './billLogDraw.vue';
import { indexOf } from 'lodash-es';
const { handleExportXls, handleExportXlsx,handleImportXls } = useMethods();

const [registerBillLogDraw, openBillLogDraw ] = useDrawer();
const { createConfirm, createMessage } = useMessage();
const queryParam = reactive<any>({});
const userStore = useUserStore();
 
const props = defineProps({
  pageType: { type: String, default: '0' },
});
const uploading = ref(false);
const percent = ref(0);
function handleLog(record) {
  openBillLogDraw.openDrawer(true, {
    orderCode: record.orderCode
  })
}
const onHandleChange = (info) => {
  console.log(1);
  
  uploading.value = true;
}
// 自动请求并暴露内部方法
onMounted(() => {
  pageType.value = props.pageType;
});

//页面类型读取
const getProps = (val?) => {
  if (!!val) {
    return props.pageType === val;
  }
  return props.pageType === '0';
}

//注册model
const [submitPaymentModal, submitPaymentUseModal] = useModal();
const [submitAuditModal, submitAuditUseModal] = useModal();
const [registerModal, { openModal }] = useModal();
const [registerModal2, openModal2] = useModal();
//注册table数据
const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    title: '订单列表',
    api: list,
    columns: columns,
    canResize: false,
    formConfig: {
      //labelWidth: 120,
      schemas: uniFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      fieldMapToNumber: [
      ],
      fieldMapToTime: [
        ['createTime', ['createTime_begin', 'createTime_end'], 'YYYY-MM-DD'],
        ['paymentTime', ['paymentTime_begin', 'paymentTime_end'], 'YYYY-MM-DD'],
        ['auditTime', ['auditTime_begin', 'auditTime_end'], 'YYYY-MM-DD'], 
      ],
    },
    actionColumn: {
      width: 250,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: undefined,
    },
    beforeFetch: (params) => {
      params.pageType = props.pageType; //带上页面类型参数
      return Object.assign(params, queryParam);
    },
    // 显示底部合计
    showSummary: true,
    // 底部合计计算方法
    summaryFunc: onSummary,
  },
  exportConfig: {
    name: "采购订单",
    url: getExportUrl,
    params: queryParam,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess
  },
  
})

const [registerTable, { reload }, { rowSelection, selectedRowKeys, selectedRows }] = tableContext

// 高级查询配置
const superQueryConfig = reactive(superQuerySchema);

/**
 * 高级查询事件
 */
function handleSuperQuery(params) {
  Object.keys(params).map((k) => {
    queryParam[k] = params[k];
  });
  reload();
}
import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
function copys(text) {
  const { isSuccessRef } = useCopyToClipboard(text);
  //console.log(isSuccessRef);

}
/**
 * 新增事件
 */
function handleAdd() {
  openModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}
/**
 * 详情
*/
function handleDetail(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: false,
  });
}
/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id }, handleSuccess);
}
/**
 * 批量删除事件
 */
async function batchHandleDelete() {
  await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
}


/**
 * 批量提交
 */
 async function batchHandleSumbit() {
  let isFLa = true
  selectedRows.value?.forEach(item => {
    if (item.auditState != "-1") {
      isFLa = false
    }
  })
  if (isFLa) {
    createConfirm({
      iconType: 'warning',
      title: '确认批量提交',
      content: '是否批量提交选中数据',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        await sumbitOk({ id: selectedRowKeys.value?.join(',') });
        handleSuccess()
        return;
      }
    });

  } else {
    createMessage.warning('已经提交的不能操作！')
  }
}

/**
 * 批量订单审核
 */
async function batchHandleAudit() {
  let isFLa = true
  selectedRows.value?.forEach(item => {
    if (item.auditState === "1") {
      isFLa = false
    }
  })
  if (isFLa) {
    submitAuditUseModal.openModal(true, {
      title: '批量订单审核',
      record: { id: selectedRowKeys.value?.join(',') },
    });
    // createConfirm({
    //   iconType: 'warning',
    //   title: '确认批量订单确认',
    //   content: '是否批量订单确认选中数据',
    //   okText: '确认',
    //   cancelText: '取消',
    //   onOk: async () => {
    //     await audit({ id: selectedRowKeys.value?.join(',') });
    //     handleSuccess()
    //     return;
    //   }
    // });

  } else {
    createMessage.warning('已经审批通过的不能操作！')
  }
}


/**
 * 批量支付确认
 */
async function batchHandlePayment() {
  let isFLa = true
  selectedRows.value?.forEach(item => {
    if (item.auditState != "1" || item.paymentState === "1") {
      isFLa = false
    }
  })
  if (isFLa) {
    createConfirm({
      iconType: 'warning',
      title: '确认批量支付确认',
      content: '是否批量支付确认选中数据',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        await payment({ id: selectedRowKeys.value?.join(',') });
        handleSuccess()
        return;
      }
    });
  } else {
    createMessage.warning('不是订单确认通过和已支付确认的不能操作！')
  }
}



/**
 * 订单提交
 */
async function handleSubmitOne(record) {
  const resultInfo = await sumbitOk({ id: record.id });
   console.log("----"+resultInfo)
  handleSuccess()
}


/**
 * 订单审核
 */
async function handleAudit(record) {
  // await audit({ id: record.id });
  // handleSuccess()
  submitAuditUseModal.openModal(true, {
      title: '订单审核',
      record: { id: record?.id },
    });
}


/**
 * 支付确认
 */
async function handlePayment(record) {
  await payment({ id: record.id });
  handleSuccess()
}
//标记欠款
async function handleTagDebt(record) {
  await payment({ id: record.id });
  handleSuccess()
}

/**
 * 发货
 */
async function handleShipment(record) {
  record.orderCreateBy = record.createBy
  openModal2.openModal(true, {
    record,
  });
  // await shipment({ id: record.id });
  // handleSuccess();
}


/**
 * 收货
 */
 async function handleshouhuo(record) {
  await shouhuo({ id: record.id });
  handleSuccess();
}

 
/**
 * 支付凭证
 */
async function handleSubmitPayment(record) {

  submitPaymentUseModal.openModal(true, {
    title: '支付凭证提交',
    record: { id: record.id, orderCode: record.orderCode, totalRealAmount: record.totalRealAmount },
  });
}

/**
 * PDF导出
 */
async function handleExcelConfigId(record) {
  var info = await exportPdfStream({
    excelConfigId: "1011051575872913408",
    queryParam: {
      receiptZone: getAreaTextByCode(record?.receiptZone),
      orderCode: record?.orderCode,
      token: userStore.getToken,
      pageNo: "1",
      pageSize: 10,
      currentPageNo: "1",
      currentPageSize: 10
    }
  })
  // 创建 Blob 对象
  const blob = new Blob([info], { type: 'application/pdf' });

  // 创建下载链接
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = '订单出库单.pdf'; // 设置下载文件名
  document.body.appendChild(link);
  link.click(); // 触发下载
  document.body.removeChild(link); // 移除链接

  // 释放 Blob URL
  URL.revokeObjectURL(link.href);
}

/**
 * 收货凭证
 */
//  async function handleSubmitTakeDelivery(record) {
//   submitTakeDeliveryUseModal.openModal(true, {
//     title: '收货凭证提交',
//     record: {id: record?.id},
//   });
// }
/**
  * 计算合计
  * @param tableData
  */
import { mapTableTotalSummary } from '/@/utils/common/compUtils';
function onSummary(tableData: Recordable[]) {
  // 可用工具方法自动计算合计
  const totals = mapTableTotalSummary(tableData, ['totalAmount']);
  return [{
      _row: '合计',
      _index: '合计',
    storeName: totals.totalAmount.toFixed(2) + "元"
    }
  ];
}

/**
 * 成功回调
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}
/**
   * 操作栏
   */
function getTableAction(record) {
  return [
    {
      label: '日志',
      onClick: handleLog.bind(null, record),
    },
    {
      label: '编辑',
      ifShow: record.orderStatus === "待提交" && getProps(),
      onClick: handleEdit.bind(null, record),
      auth: 'lx:xl_customer_orde:edit'
    },
    {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    },
    {
      label: '提交',
      ifShow: record.orderStatus === "待提交",
      onClick: handleSubmitOne.bind(null, record),
      auth: 'lx:xl_customer_orde:submit'
    },
    // {
    //   label: '出库单导出',
    //   ifShow: !!record.auditState,
    //   onClick: handleExcelConfigId.bind(null, record),
    //   auth: 'lx:xl_customer_orde:pdfExport'
    // },
    {
      label: '订单审核',
      ifShow: record.orderStatus === "待审核" && getProps('1'),
      onClick: handleAudit.bind(null, record),
      auth: 'lx:xl_customer_orde:audit'
    }
    ,
    // {
    //   label: '支付确认',
    //   ifShow: record.auditState === "1" && record.paymentState === "0" && getProps('4'),
    //   onClick: handlePayment.bind(null, record),
    //   auth: 'lx:xl_customer_orde:payment'
    // }
    // ,
    // {
    //   label: '发货',
    //   ifShow: record.auditState === "1" && record.shipmentState != "1" && getProps('6'),
    //   onClick: handleShipment.bind(null, record),
    //   auth: 'lx:xl_customer_orde:shipment'
    // },
    // {
    //   label: '收货',
    //   ifShow: record.shipmentState === "1" && record.takeDeliveryState === "0" && getProps('10'),
    //   onClick: handleTakeDelivery.bind(null, record),
    //   auth: 'lx:xl_customer_orde:takeDelivery'
    // },
    {
      label: '支付凭证',
      ifShow: getProps('3') && (record.orderStatus === "待支付" || record.isDebt === "欠款送审"),
      onClick: handleSubmitPayment.bind(null, record),
      auth: 'lx:xl_customer_orde:submitPayment'
    }
    ,
    {
      label: '欠款送审',
      ifShow: getProps('3') && record.orderStatus === "待支付",
      onClick: handleTagDebt.bind(null, record),
      auth: 'lx:xl_customer_orde:submitPayment'
    }
    ,
    {
      label: '收货',
      ifShow: getProps('8') && record.orderStatus === "待收货",
      onClick: handleshouhuo.bind(null, record),
      auth: 'lx:xl_customer_orde:submitPayment'
    }
    ,
    // {
    //   label: '收货凭证',
    //   ifShow: record.shipmentState === "1" && !record.takeDeliveryState && getProps('7'),
    //   onClick: handleSubmitTakeDelivery.bind(null, record),
    //   auth: 'lx:xl_customer_orde:submitTakeDelivery'
    // },

    {
      label: '删除',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(null, record),
        placement: 'topLeft'
      },
      ifShow: !record.auditState && getProps(),
      auth: 'lx:xl_customer_orde:delete'
    },
  ]
}


/**
 * 下拉操作栏
 */
function getDropDownAction(record) {
  return [
  ]
}
const [registerDetailModal1, detailModel1] = useModal();
function handleDetailS(orderCode, logiStr) {
  let s = logiStr.split(":");
  let cord = { orderCode: orderCode, logiCom: s[0], logiOrder: s[1] };


  detailModel1.openModal(true, {
    record: cord,
  });
}

function importLogiCode(file) {
  handleImportXls(file, '/slt/logicmana/importExcel', '').then(() => {
    handleSuccess();
  });
}
</script>

<style lang="less" scoped>
:deep(.ant-picker),
:deep(.ant-input-number) {
  width: 100%;
}
</style>
